﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using B4Deal.Models;
using Webdiyer.WebControls.Mvc;
using System.IO;
namespace B4Deal.Controllers
{
    public class HomeController : Controller
    {
        B4Deal_DataEntities db = new B4Deal_DataEntities();
        UserManager userManager = new UserManager();

        public ActionResult Index()
        {
            int id = Convert.ToInt32(Request.QueryString["place"]);
            if(id == null || id == 1)
                return View(Deal.GetDeals(20, 1));
            return View(Deal.GetDeals(20, 1));
        }

        string strResource = "../../Content/Layout/Images/deals/";
        private List<Deal> GetDeals(int i)
        {
            List<Deal> deals = new List<Deal>();
            foreach (var deal in db.KHUYENMAIs)
            {
                if (deals.Count < i)
                    deals.Add(new Deal(deal.MaKM, Convert.ToInt32(deal.LoaiKM), deal.TenKM, Convert.ToInt32(deal.DonGiaCu), Convert.ToInt32(deal.DonGiaMoi), Convert.ToDateTime(deal.KetThucKM),
                                       deal.MoTa, deal.DiemNoiBat, deal.DKSuDung, deal.GioiThieuChiTiet,
                                       Convert.ToInt32(deal.DoanhNghiep), strResource + deal.HinhAnh, strResource + deal.ClipQuangCao, Convert.ToInt32(deal.HinhThucGiaoSP), Convert.ToInt32(deal.TinhTrang), deal.DONHANGs.Count, 1000));
            }
            return deals;
        }

        public ActionResult Thank(int id)
        {
            /*String transaction_info = Request.QueryString["transaction_info"];
            String order_code = Request.QueryString["order_code"];
            String payment_id = Request.QueryString["payment_id"];
            String payment_type = Request.QueryString["payment_type"];
            String secure_code = Request.QueryString["secure_code"];
            String price = Request.QueryString["price"];
            String error_text = Request.QueryString["error_text"];
            NL_Checkout nl = new NL_Checkout();
            check = nl.verifyPaymentUrl(transaction_info, order_code, price, payment_id, payment_type, error_text, secure_code);
            */
            // (String transaction_info, String order_code, String price, String payment_id, String payment_type, String error_text, String secure_code)
            Object y = id;
            return View(y);
        }
        public ActionResult DetailDeal(int? id)
        {
            return View(QueryDealById(Convert.ToInt32(id)));
        }
        public ActionResult Profile()
        {
            return View();
        }

        public ActionResult ListDeals(int? id)
        {
            int temp = 1;
            if (id > 1 && id != null)
                temp = Convert.ToInt32(id);
            PagedList<Deal> deals = new PagedList<Deal>(Deal.GetDeals(45, 1), temp, 15);
            if (Request.IsAjaxRequest())
            {
                return PartialView("_DealPage", deals);
            }
            return View(deals);
        }

        private Deal QueryDealById(int id)
        {
            var temp = db.KHUYENMAIs.Where(x => x.MaKM.Equals(id)).Take(1).ToList()[0];
            return new Deal(temp.MaKM, Convert.ToInt32(temp.LoaiKM), temp.TenKM, Convert.ToInt32(temp.DonGiaCu), Convert.ToInt32(temp.DonGiaMoi), Convert.ToDateTime(temp.KetThucKM),
                                       temp.MoTa, temp.DiemNoiBat, temp.DKSuDung, temp.GioiThieuChiTiet,
                                       Convert.ToInt32(temp.DoanhNghiep), strResource + temp.HinhAnh, strResource + temp.ClipQuangCao, Convert.ToInt32(temp.HinhThucGiaoSP), Convert.ToInt32(temp.TinhTrang), temp.DONHANGs.Count, 1000);
        }

        //------------------------Cart-------------------------------
        [HttpPost]
        public ActionResult getCart()
        {
            if (Request.IsAjaxRequest())
            {
                //Get cart
                if (Session["user"] != null)
                {
                    String email = Session["user"].ToString();
                    List<CartInfo> deals;
                    if (Session[email] != null)
                        deals = (List<CartInfo>)Session[email];
                    else
                        deals = new List<CartInfo>();
                    List<miniProduct> model = Convert2CartProduct(deals);
                    String par = RenderPartialViewToString(this, "_cart", model);
                    return Json(new { rs = "success", partial = par });
                }
                return Json(new { rs = "fail" });
            }
            return View();
        }

        [HttpPost]
        public ActionResult GetDealFromCart()
        {
            if (Request.IsAjaxRequest())
            {
                //Get cart
                if (Session["user"] != null)
                {
                    String email = Session["user"].ToString();
                    List<CartInfo> deals;
                    if (Session[email] != null)
                        deals = (List<CartInfo>)Session[email];
                    else
                        deals = new List<CartInfo>();
                    List<Deal> model = Convert2Deal(deals);
                    string title = String.Empty;
                    int value = 0;
                    foreach (var deal in model)
                    {
                        int sl = deals.Find((i) => i.MaKhuyenMai == deal.MaKM).SoLuong;
                        title += deal.TenKM + " | ";
                        value += deal.DonGiaMoi * sl;
                    }

                    title = title.Substring(0, title.LastIndexOf('|')).Trim();
                    return Json(new { rs = "success", tt = title, val = value.ToString() });
                }
                return Json(new { rs = "fail" });
            }
            return View();
        }

        [HttpPost]
        public ActionResult RegisterGetDeal(string emailRegis)
        {
            if (Request.IsAjaxRequest())
            {
                Email email = new Email();
                email.strEmail = emailRegis;
                String rs = "";
                bool sc = false;
                try
                {
                    sc = email.RegisterGetDeal();
                }
                catch (Exception ex)
                {
                    rs = ex.Message.ToString();
                }
                if (sc)
                    rs = "success";
                return Json(new { result = rs });
            }
            return View();
        }

        [HttpPost]
        public ActionResult SendComment(string comment, string account, string maSP)
        {
            if (Request.IsAjaxRequest())
            {
                TAIKHOAN user = userManager.GetUser(account);

                Comment cm = new Comment(comment, DateTime.Now, user.MaTK);
                cm.MaKM = Int32.Parse(maSP);
                String rs = "";
                bool sc = false;
                try
                {
                    sc = cm.SendComment();
                }
                catch (Exception ex)
                {
                    rs = ex.Message.ToString();
                }
                if (sc)
                    rs = "success";
                return Json(new { result = rs });
            }
            return View();
        }

        public ActionResult Payment()
        {
            if (Session["user"] != null)
            {
                String email = Session["user"].ToString();
                TAIKHOAN user = userManager.GetUser(email);
                return View(user);
            }
            return View(new TAIKHOAN());
            //return View(new User(1, "Ngo Trong Nghia", "trongnghia09ctt2@gmail.com", "xxx", true, DateTime.Today, 1));
        }

        [HttpPost]
        public ActionResult PayCart()
        {
            String email = Session["user"].ToString();
            TAIKHOAN user = userManager.GetUser(email);
            if (Request.IsAjaxRequest())
            {
                List<CartInfo> carts = (List<CartInfo>)Session[email];
                if (carts == null) //không có mặt hàng
                    return Json(new { rs = "fail" });
            }
            return Json(new { rs = "success" });
            //return View(new User(1, "Ngo Trong Nghia", "trongnghia09ctt2@gmail.com", "xxx", true, DateTime.Today, 1));
        }

        [HttpPost]
        public ActionResult AddOrder()
        {
            if (Request.IsAjaxRequest())
            {
                String email = Session["user"].ToString();
                TAIKHOAN user = userManager.GetUser(email);
                List<CartInfo> carts = (List<CartInfo>)Session[email];
                Order od = new Order();
                //Set Orders                    
                od.MaTK = user.MaTK;
                od.HinhThucThanhToan = Int32.Parse(Request.Form["PTTT"].ToString());
                od.GhiChu = Request.Form["txtDesc_0"].ToString();
                String rs = "success";
                try
                {
                    String Mail = Request.Form["txtEmail_0"].ToString();
                    String Name = Request.Form["txtName_0"].ToString();
                    String Phone = Request.Form["txtPhone_0"].ToString();
                    String sonha = Request.Form["txtSoNha_0"].ToString();
                    String duong = Request.Form["txtDuong_0"].ToString();
                    String phuong = Request.Form["txtWard_0"].ToString();
                    String quan = Request.Form["txtQuan_0"].ToString();
                    String toanha = Request.Form["txtBuilding_0"].ToString();
                    if (String.IsNullOrEmpty(duong) || String.IsNullOrEmpty(phuong) ||
                        String.IsNullOrEmpty(quan) || String.IsNullOrEmpty(sonha) ||
                        String.IsNullOrEmpty(Mail) || String.IsNullOrEmpty(Name) ||
                        String.IsNullOrEmpty(Phone))
                        return Json(new { result = "Bạn phải điền đầy đủ các thông tin nhận hàng bắt buộc!" });
                    //Save Receiver
                    String Address = "";
                    if (toanha != null)
                        Address += "Toà nhà: " + toanha + ", ";
                    Address += sonha + ", " + duong + ", " + phuong + ", " + quan;
                    od.SaveReceiver(Mail, Name, Phone, Address);

                    foreach (CartInfo i in carts)
                    {
                        od.MaKM = i.MaKhuyenMai;
                        od.SoLuong = i.SoLuong;
                        od.SaveOrders();
                    }
                }
                catch (Exception ex)
                {
                    rs = ex.Message.ToString();
                }
                return Json(new { result = rs });
            }
            return View();
        }

        private List<Deal> Convert2Deal(List<CartInfo> carts)
        {
            List<Deal> deals = new List<Deal>();
            if (carts.Count > 0)
                foreach (Deal d in Deal.GetDeals(20, 1))
                {
                    if (carts.Exists((i) => i.MaKhuyenMai == d.MaKM))
                        deals.Add(d);
                }
            return deals;
        }

        private List<miniProduct> Convert2CartProduct(List<CartInfo> carts)
        {
            List<miniProduct> lst = new List<miniProduct>();
            List<Deal> deals = new List<Deal>();
            if (carts.Count > 0)
                foreach (Deal d in Deal.GetDeals(20, 1))
                {
                    if (carts.Exists((i) => i.MaKhuyenMai == d.MaKM))
                        deals.Add(d);
                }
            foreach (Deal d in deals)
            {
                miniProduct mini = new miniProduct();
                mini.MaKM = d.MaKM;
                mini.MoTa = d.MoTa;
                mini.HinhAnh = d.HinhAnh;
                mini.TenKM = d.TenKM;
                mini.ThoidiemThem = new DateTime();
                mini.DonGiaMoi = (int)d.DonGiaMoi;
                mini.SoLuong = carts.Find((i) => i.MaKhuyenMai == mini.MaKM).SoLuong;
                lst.Add(mini);
            }
            return lst;
        }

        public string RenderPartialViewToString(Controller controller, string viewName, object model)
        {
            controller.ViewData.Model = model;
            try
            {
                using (StringWriter sw = new StringWriter())
                {
                    ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(controller.ControllerContext, viewName);
                    ViewContext viewContext = new ViewContext(controller.ControllerContext, viewResult.View, controller.ViewData, controller.TempData, sw);
                    viewResult.View.Render(viewContext, sw);

                    return sw.GetStringBuilder().ToString();
                }
            }
            catch (Exception ex)
            {
                return ex.ToString();
            }
        }

        [HttpPost]
        public ActionResult AddCartItem(int maKM)
        {
            if (Request.IsAjaxRequest())
            {
                if (Session["user"] != null)
                {
                    String email = Session["user"].ToString();
                    List<CartInfo> carts;
                    if (Session[email] == null)
                    {
                        carts = new List<CartInfo>();
                        Session[email] = carts;
                    }
                    else
                        carts = (List<CartInfo>)Session[email];
                    CartInfo item = carts.Find((i) => i.MaKhuyenMai == maKM);
                    if (item == null)
                        carts.Add(new CartInfo(maKM, 1));
                    else
                        item.SoLuong++;
                    List<miniProduct> model = Convert2CartProduct(carts);
                    String par = RenderPartialViewToString(this, "_cart", model);
                    return Json(new { rs = "success", partial = par });
                }
            }
            return View();
        }

        [HttpPost]
        public ActionResult ClearCart()
        {
            if (Request.IsAjaxRequest())
            {
                if (Session["user"] != null)
                {
                    String email = Session["user"].ToString();
                    Session[email] = null;
                    List<miniProduct> model = new List<miniProduct>();
                    String par = RenderPartialViewToString(this, "_cart", model);
                    return Json(new { rs = "success", partial = par });
                }
            }
            return View();
        }

        [HttpPost]
        public ActionResult getDetail(int order)
        {
            if (Request.IsAjaxRequest())
            {
                //Get order detail
                if (Session["user"] != null)
                {
                    String email = Session["user"].ToString();
                    TAIKHOAN user = userManager.GetUser(Session["user"].ToString());
                    List<Order> o = userManager.GetOrdersByUser(user);
                    Order model = o.Find((it) => it.MaDH == order);
                    String par = RenderPartialViewToString(this, "_DetailOrder", model);
                    return Json(new { rs = "success", partial = par });
                }
                return Json(new { rs = "fail" });
            }
            return View();
        }

        [HttpPost]
        public ActionResult getCreateView()
        {
            if (Request.IsAjaxRequest())
            {
                String email = Session["user"].ToString();
                TAIKHOAN user = userManager.GetUser(Session["user"].ToString());
                //Get order detail
                if (Session["user"] != null && userManager.checkBusiness(user))
                {
                    Deal deal = new Deal();
                    String par = RenderPartialViewToString(this, "_CreateDeal", deal);
                    return Json(new { rs = "success", partial = par });
                }
                return Json(new { rs = "fail", partial = "Bạn chưa đăng ký tài khoản doanh nghiệp" });
            }
            return View();
        }

        [HttpPost]
        public ActionResult AddDeals()
        {
            String email = Session["user"].ToString();
            TAIKHOAN user = userManager.GetUser(Session["user"].ToString());
            if (Request.IsAjaxRequest() && userManager.checkBusiness(user))
            {
                if (Session["user"] != null)
                {
                    String nameKM = Request.Form["txtName"].ToString();
                    String oldPrice = Request.Form["txtGiaCu"].ToString();
                    String newPrice = Request.Form["txtGiaMoi"].ToString();
                    String startDate = Request.Form["txtNgayBD"].ToString();
                    String endDate = Request.Form["txtNgayKT"].ToString();
                    String description = Request.Form["txtMoTa"].ToString();
                    String special = Request.Form["txtNoiBat"].ToString();
                    String condition = Request.Form["txtDieuKien"].ToString();
                    String detail = Request.Form["txtChiTiet"].ToString();
                    String image = Request.Form["txtHinhAnh"].ToString();

                    if (String.IsNullOrEmpty(nameKM) || String.IsNullOrEmpty(newPrice) ||
                        String.IsNullOrEmpty(startDate) || String.IsNullOrEmpty(endDate) ||
                        String.IsNullOrEmpty(description) || String.IsNullOrEmpty(special) ||
                        String.IsNullOrEmpty(condition) || String.IsNullOrEmpty(detail))
                        return Json(new { rs = "fail", detail = "Bạn phải điền đầy đủ các thông tin bắt buộc *!" });

                    bool sc = false;
                    try
                    {
                        //Add
                        Deal deal = new Deal();
                        deal.TenKM = nameKM;
                        deal.MoTa = description;
                        deal.DkSuDung = condition;
                        deal.GioiThieuChiTiet = detail;
                        deal.DacDiemNoiBat = special;
                        deal.DonGiaMoi = Int32.Parse(newPrice);
                        deal.MaDN = userManager.getBusiness(user).MaDN;
                        deal.BatDauKM = DateTime.ParseExact(startDate, "d/M/yyyy", null);
                        deal.KetThucKM = DateTime.ParseExact(endDate, "d/M/yyyy", null);
                        if (image != null)
                            deal.HinhAnh = image;
                        if (oldPrice != null)
                            deal.DonGiaCu = Int32.Parse(oldPrice);

                        sc = deal.SaveDeal();
                    }
                    catch (Exception ex)
                    {
                        return Json(new { rs = "fail", detail = ex.Message });
                    }
                    if (!sc)
                        return Json(new { rs = "fail", detail = "Có lỗi xảy ra khi cập nhật! Vui lòng thử lại!" });
                    return Json(new { rs = "success", detail = "Lưu thông tin thành công!" });
                }
            }
            return View();
        }
    }
}
